/* eslint-disable no-console */

/**
 * Export types for tax forms to easily retrieve them in other services.
 */

import path from 'path';

import ts from 'typescript';

const basePath = 'components/dashboard/sections/tax-information';

const types = [
  {
    file: path.join(basePath, 'common.ts'),
    export: '*',
  },
  {
    file: path.join(basePath, 'W9Form.tsx'),
    export: 'W9TaxFormValues',
  },
  {
    file: path.join(basePath, 'W8BenForm.tsx'),
    export: 'W8BenTaxFormValues',
  },
  {
    file: path.join(basePath, 'W8BenEForm.tsx'),
    export: 'W8BenETaxFormValues',
  },
];

const program = ts.createProgram(
  types.map(type => type.file),
  {},
);
const checker = program.getTypeChecker();

function getTypeInfo(filePath: string, typeName: string): void {
  // Find the specified type in the file
  for (const sourceFile of program.getSourceFiles()) {
    if (sourceFile.fileName.includes(filePath)) {
      ts.forEachChild(sourceFile, node => {
        const isTypeAlias = ts.isTypeAliasDeclaration(node);
        const isEnum = ts.isEnumDeclaration(node);
        if ((isTypeAlias || isEnum) && (node.name.text === typeName || typeName === '*')) {
          const type = checker.getTypeAtLocation(node.name);

          if (isEnum) {
            console.log(`${node.getText()}\n`);
          } else if (isTypeAlias) {
            const typeInfo = checker.typeToString(type, undefined, ts.TypeFormatFlags.NoTruncation);
            console.log(`export type ${node.name.text} = ${typeInfo}\n`);
          }
        }
      });
    }
  }
}

console.log('// This file is auto-generated by opencollective-frontend/scripts/export-tax-form-types.ts\n');
types.forEach(type => {
  getTypeInfo(type.file, type.export);
});
